package org.singledog.form.builder.parser.freemarker.parser;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.singledog.form.builder.ComponentType;
import org.singledog.form.builder.MagicConstants;
import org.singledog.form.builder.parser.freemarker.view.DialogView;
import org.singledog.form.builder.view.View;

public class DialogComponentParser extends AbstractFreemarkerParser {

    private FormComponentParser formComponentParser = new FormComponentParser();

    private DataGridComponentParser dataGridComponentParser = new DataGridComponentParser();

    @Override
    public ComponentType supportType() {
        return ComponentType.dialog;
    }

    @Override
    public View parseView(String code) {
        String json = getSchema(code);
        JSONObject object = JSON.parseObject(json);
        object.put(MagicConstants.VIEW_CODE, code);

        JSONObject schema = null;
        String contentCode = object.getString("contentCode");
        String contentType = object.getString("content");

        if (StringUtils.equals(MagicConstants.FORM, contentType)) {
            String formJson = formComponentParser.getSchema(contentCode);
            schema = JSON.parseObject(formJson);
        } else if (StringUtils.equals(MagicConstants.DATAGRID, contentType)) {
            String formJson = dataGridComponentParser.getSchema(contentCode);
            schema = JSON.parseObject(formJson);
        } else {
            schema = new JSONObject();
        }

        schema.put(MagicConstants.DIALOG, object);
        schema.put(MagicConstants.VIEW_CODE, contentCode);

        return new DialogView(code, schema);
    }
}
